<?php
/**
 * author by OCY, 2025/03/28 00:16.
 */

namespace profit;

use think\Db;
use think\Exception;

class Profit
{
    private $v1_to_v6_share_rate_config; // 实时结算v1至v6的分佣比例配置(%)
    private $jtjz_share_rate_config; // 家庭酒庄分佣比例配置(%)
    private $total_revenue_share_rate; // 分红池总营收分红比例（%）
    private $v6_to_v1_revenue_share_rate; // 分红池V6-V1各级分红比例
    private $agent_share_rate; // 分佣用户列表


    public function __construct()
    {
        // 实时结算v1至v6的分佣比例配置(%)
        $this->v1_to_v6_share_rate_config = [5, 10, 15, 17, 19, 20];
        // 家庭酒庄分佣比例配置(%)
        $this->jtjz_share_rate_config = 5;
        // 分红池总营收分红比例（%）
        $this->total_revenue_share_rate = 5;
        // 分红池V6-V1各级分红比例（%）
        $this->v6_to_v1_revenue_share_rate = [5, 5, 10, 20, 30, 30];
        // 区县代理商分佣比例（%）
        $this->agent_share_rate = 5;
    }

    /**
     * 获取V1-V6分佣用户列表
     * */
    public function getShareUserList($user_id)
    {
        $user_list = [];
        $parent_ids = Db::name('user')->where('id', $user_id)->value('parent_ids');
        if ($parent_ids = preg_replace('/^,0,|,$/', '', $parent_ids)) {
            $list = Db::name('user')->field('id,user_level,h5_money,score')->whereIn('id', $parent_ids)->order('id desc')->select();
            if ($list) {
                $prev_user_level = 0;
                foreach ($list as $v) {
                    if ($v['user_level'] > $prev_user_level) {
                        $prev_user_level = $v['user_level'];
                        $user_list[] = [
                            'user_id' => $v['id'],
                            'level' => $v['user_level'],
                            'h5_money' => $v['h5_money'],
                            'score' => $v['score']
                        ];

                        if ($prev_user_level == 6) break;
                    }
                }
            }
        }
        return $user_list;
    }

    /**
     * 下单收益实时结算
     * @param int   $id          订单id（wechat_orders表主键id）
     * @param array $v_user_list 分佣用户信息(V1-V6) [[user_id, level, h5_money, score], [user_id, level, h5_money, score]] => user_id 用户id, level 用户等级, h5_money h5余额钱包，score 小程序兑换积分
     * @param array $user_info   分佣用户信息(家庭酒庄) [user_id, expert_level, h5_money, score]
     * @return array
     * */
    public function profitShare($id, $v_user_list = [], $user_info = [])
    {
        if ($id) {
            $money = Db::name('wechat_orders')->where('id', $id)->value('order_price');

            if ($money > 0) {
                if ($v_user_list) {
                    // level v1-v6的等级取值1-6
                    $user_data = [];
                    $money_log_data = [];
                    $score_log_data = [];
                    $prev_rate = 0;
                    $time = time();
                    foreach ($v_user_list as $v) {
                        // 当前等级分佣比例
                        $level_rate = $this->v1_to_v6_share_rate_config[$v['level'] - 1];
                        if ($level_rate > $prev_rate) {
                            // 实际分佣比例（极差分佣）
                            $share_rate = $level_rate - $prev_rate;
                            // 收益
                            $share_money = ($money * $share_rate / 100);
                            // 90%收益到H5余额钱包
                            $share_money = $share_money * 0.9;
                            // 10%收益到小程序的兑换积分钱包
                            $share_score = intval($share_money * 0.1);

                            $prev_rate = $level_rate;

                            $data = $this->createData($id, $v['user_id'], $v['h5_money'], $v['score'], $share_money, $share_score);
                            $user_data[] = $data['user_data'];
                            $money_log_data[] = $data['money_log_data'];
                            if ($data['score_log_data']) $score_log_data[] = $data['score_log_data'];
                        }
                    }
                }

                if ($user_info) {
                    // 家庭酒庄分佣
                    $share_money = $money * $this->jtjz_share_rate_config / 100;
                    // 90%收益到H5余额钱包
                    $share_money = $share_money * 0.9;
                    // 10%收益到小程序的兑换积分钱包
                    $share_score = intval($share_money * 0.1);

                    $data = $this->createData($id, $user_info['user_id'], $user_info['h5_money'], $user_info['score'], $share_money, $share_score);
                    $jtjz_user_data = $data['user_data'];
                    $user_index = array_search($jtjz_user_data['user_id'], array_column($user_data, 'user_id'));
                    if ($user_index !== false) {
                        // 拿家庭酒庄补贴的用户在上面的V1-V6中，直接累加余额和积分
                        $user_data[$user_index]['share_money'] += $share_money;
                        $user_data[$user_index]['share_score'] += $share_score;
                    } else {
                        $user_data[] = $jtjz_user_data;
                    }

                    $money_log_data[] = $data['money_log_data'];
                    if ($data['score_log_data']) $score_log_data[] = $data['score_log_data'];
                }

                Db::startTrans();
                try {
                    if ($user_data) {
                        foreach ($user_data as $v) {
                            $update_user_data = [
                                'h5_money' => $v['h5_money'] + $v['share_money'], // h5余额钱包
                                'score' => $v['score'] + $v['share_score'], // 小程序兑换积分
                                'update_time' => $time
                            ];

                            Db::name('user')->where('id', $v['user_id'])->update($update_user_data);
                        }

                        Db::name('mini_user_money_log')->insertAll($money_log_data);
                        Db::name('mini_user_score_log')->insertAll($score_log_data);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                }
            }
        }
    }

    public function createData($id, $user_id, $h5_money, $score, $share_money, $share_score, $is_jtjz = false)
    {
        $time = time();

        $user_data = [
            'user_id' => $user_id,
            'h5_money' => $h5_money,
            'score' => $score,
            'share_money' => $share_money,
            'share_score' => $share_score
        ];

        $money_log_data = [
            'user_id' => $user_id,
            'money' => $share_money,
            'before' => $h5_money,
            'after' => $h5_money + $share_money,
            'type' => $is_jtjz ? 5 : 2,
            'remark' => $is_jtjz ? '家庭酒庄补贴' : '实时结算收益',
            'create_time' => $time,
            'link_id' => $id,
            'link_table' => 'fa_wechat_orders',
            'from' => 1,
        ];

        $score_log_data = [];
        if ($share_score > 0) {
            $score_log_data = [
                'user_id' => $user_id,
                'score' => $share_score,
                'before' => $score,
                'after' => $score + $share_money,
                'type' => $is_jtjz ? 5 : 1,
                'remark' => $is_jtjz ? '家庭酒庄补贴' : '实时结算收益',
                'create_time' => $time,
                'link_id' => $id,
                'link_table' => 'fa_wechat_orders',
                'from' => 1,
            ];
        }

        return [
            'user_data' => $user_data,
            'money_log_data' => $money_log_data,
            'score_log_data' => $score_log_data
        ];
    }

    /**
     * 分红池结算
     * 月结：V6至V1逐级分红，高级别可以重复在低级别分红
     * */
    public function revenueSettlement()
    {

    }

    /**
     * 区县代理商结算
     * 月结：按区域结算
     * */
    public function agentSettlement()
    {

    }


}